# -*- coding: utf-8 -*-

# 地牢游戏

import sys, time, random, math, pygame
from pygame.locals import *
from MyLibrary import *
from datetime import datetime, date, time
from Dungeon import *
from Player import *

reload(sys)
sys.setdefaultencoding('utf-8')

screen_width = 700
screen_height = 660
TILE_EMPTY = 176
TILE_ROOM = 219
TILE_HALL = 178
TILE_PORTAL_UP = 30
TILE_PORTAL_DOWN = 31

def playerCollision(stepx, setpy):
    global TILE_EMPTY, TILE_ROOM, TILE_HALL, dungeon, player, level
    yellow = (220, 220, 0)
    green = (0, 220, 0)

    # get object at location
    char = dungeon.getCharAt(player.x + stepx, player.y + setpy)

    if char == TILE_PORTAL_UP:
        print('portal up')
    elif char == TILE_PORTAL_DOWN:
        print('portal down')
    elif char == TILE_EMPTY:
        print('You ran into the wall--ouch!')

    elif char == 71:  # gold
        gold = random.randint(1, level)
        player.gold += gold
        dungeon.setCharAt(player.x + stepx, player.y + setpy, TILE_ROOM)
        message("You found " + str(gold) + " gold!", yellow)

    elif char == 87:    # weapon
        weapon = random.randint(1, level+2)
        if level <= 5:
            temp = random.randint(0, 2)
        else:
            temp = random.randint(3, 6)
        if temp == 0: name = "Dagger"
        elif temp == 1: name = "Short Sword"
        elif temp == 2: name = "Wooden Club"
        elif temp == 3: name = "Long Sword"
        elif temp == 4: name = "War Hammer"
        elif temp == 5: name = "Battle Axe"
        elif temp == 6: name = "Halberd"
        if weapon > player.weapon:
            player.weapon = weapon
            player.weapon_name = name
            message("You found a " + name + " +" + str(weapon) + "!", yellow)
        else:
            player.gold += 1
            message("You discarded a worthless " + name + ".")
        dungeon.setCharAt(player.x + stepx, player.y + setpy, TILE_ROOM)

    elif char == 65:    # armor
        armor = random.randint(1, level+2)
        if armor <= 5:
            temp = random.randint(0, 2)
        else:
            temp = random.randint(3, 7)
        if temp == 0: name = "Cloth"
        elif temp == 1: name = "Patchwork"
        elif temp == 2: name = "Leather"
        elif temp == 3: name = "Chain"
        elif temp == 4: name = "Scale"
        elif temp == 5: name = "Plate"
        elif temp == 6: name = "Mithril"
        elif temp == 7: name = "Adamantium"
        if armor > player.armor:
            player.armor = armor
            player.armor_name = name
            message("You found a " + name + " +" + str(armor) + "!", yellow)
        else:
            player.gold += 1
            message("You discarded a worthless " + name + ".")
        dungeon.setCharAt(player.x + stepx, player.y + setpy, TILE_ROOM)

    elif char == 72:    # health
        heal = 0
        for n in range(0, level):
            heal += Die(6)
        player.addHeath(heal)
        dungeon.setCharAt(player.x + stepx, player.y + setpy, TILE_ROOM)
        message("You drank a healing potion worth " + str(heal) + " points!", green)

    elif char == 137:     # monster
        attack_monster(player.x + stepx, player.y + setpy, char)

def attack_monster(x, y, char):
    global dungeon
    monster = Monster(dungeon, level, "Grue")

    # 玩家攻击
    defense = monster.getDefense()
    attack = player.getAttack()
    damage = player.getDamage(defense)
    battle_text = "You hit the " + monster.name + " for "
    if attack == 20 + player.str:   # 暴击
        damage *= 2
        battle_text += str(damage) + " CRIT points!"
        dungeon.setCharAt(x, y, 71)     # drop gold
    elif attack > defense:
        if damage > 0:
            battle_text += str(damage) + " point."
            dungeon.setCharAt(x, y, 71)     # drop gold
        else:
            battle_text += "no damage!"
            damage = 0
    else:
        battle_text = "You missed the " + monster.name + "!"
        damage = 0

    # 怪物攻击
    defense = player.getDefense()
    attack = monster.getAttack()
    damage = monster.getDamage(defense)
    if attack > defense:
        if damage > 0:
            if damage > player.max_heath: damage /= 2
            battle_text += " It hit you for " + str(damage) + " point."
            player.addHeath(-damage)
        else:
            battle_text += " It no damage to you."
    else:
        battle_text = " It missed you."

    message(battle_text)

    if player.heath <= 0: player.alive = False

def message(msg, color=(255, 255, 255)):
    global tip_msg, tip_color
    tip_msg = msg
    tip_color = color

def game_init():
    global screen, font, timer, backbuffer, dungeon, player, tip_msg, tip_color

    pygame.init()
    winstyle = 0  # |FULLSCREEN
    bestdepth = pygame.display.mode_ok((screen_width, screen_height), winstyle, 32)
    screen = pygame.display.set_mode((screen_width, screen_height), winstyle, bestdepth)

    pygame.display.set_caption("地牢游戏")
    font = pygame.font.Font("freesansbold.ttf", 12, bold=True)
    # pygame.mouse.set_visible(False)
    timer = pygame.time.Clock()

    # 背面缓存技术
    backbuffer = pygame.Surface((screen_width, screen_height))

    dungeon = Dungeon()
    player = Player(dungeon, 1, 'Player')

    # init
    dungeon.generate(TILE_EMPTY, TILE_ROOM, TILE_HALL)  # test

    # 玩家在入口处
    player.x = dungeon.entrance_x+1
    player.y = dungeon.entrance_y+1

    tip_msg = "Welcome, brave adventurer!"
    tip_color = (0, 200, 50)

def move_monsters():
    for y in range(0, 44):
        for x in range(0, 79):
            tile = dungeon.getCharAt(x, y)
            if tile == 137:
                move_monster(x, y, tile)

def move_monster(x, y, char):
    movex = 0
    movey = 0
    dir = random.randint(1, 4)
    if dir == 1: movey = -1
    elif dir == 2: movey = 1
    elif dir == 3: movex = -1
    elif dir == 4: movex = 1
    c = dungeon.getCharAt(x+movex, y+movey)
    if c == TILE_ROOM:
        dungeon.setCharAt(x, y, TILE_ROOM)
        dungeon.setCharAt(x+movex, y+movey, char)

game_over = False
player_score = 0
enemy_score = 0
last_time = 0
mouse_x = mouse_y = 0
level = 1
tip_msg = ''
tip_color = (255, 255, 255)
game_init()

while True:
    global dungeon, player
    timer.tick(30)
    ticks = pygame.time.get_ticks()

    # reset
    mouse_up = mouse_down = 0
    mouse_up_x = mouse_up_y = 0
    mouse_down_x = mouse_down_y = 0

    for event in pygame.event.get():
        if event.type == QUIT: sys.exit()
        elif event.type == MOUSEMOTION:
            mouse_x, mouse_y = event.pos
            move_x, move_y = event.rel

    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]: sys.exit()
    elif keys[K_SPACE]:
        dungeon.generate(TILE_EMPTY, TILE_ROOM, TILE_HALL)  # test

        # 玩家在入口处
        player.x = dungeon.entrance_x
        player.y = dungeon.entrance_y
    elif keys[K_UP] or keys[K_w]:
        if player.moveUp() == False:
            playerCollision(0, -1)
        else:
            move_monsters()

    elif keys[K_DOWN] or keys[K_s]:
        if player.moveDown() == False:
            playerCollision(0, 1)
        else:
            move_monsters()

    elif keys[K_RIGHT] or keys[K_d]:
        if player.moveRight() == False:
            playerCollision(1, 0)
        else:
            move_monsters()

    elif keys[K_LEFT] or keys[K_a]:
        if player.moveLeft() == False:
            playerCollision(-1, 0)
        else:
            move_monsters()

    backbuffer.fill((0,0,0))
    dungeon.draw(backbuffer, 30, 30)
    player.draw(backbuffer, 1)

    # 绘制备份缓存
    screen.blit(backbuffer, (0, 0))

    # if not game_over:
    #     # print_text(font, 0, 0, "GAME OVER")
    #     message("GAME OVER", (222, 0, 0))

    print_text(font, 30, 30 + 45 * 12, tip_msg, tip_color)

    print_text(font, 30, 30 + 45 * 12 + 12, "weapon: " + str(player.weapon_name) + " " + str(player.weapon))
    print_text(font, 30, 30 + 45 * 12 + 12*2, "armor: " + str(player.armor_name) + " " + str(player.armor))
    print_text(font, 30, 30 + 45 * 12 + 12*3, "heath: " + str(player.heath))
    print_text(font, 30, 30 + 45 * 12 + 12*4, "gold: " + str(player.gold))

    pygame.display.update()

pygame.quit()



